package mobi.weq.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.http.HTTPException;

import mobi.weq.dao.PollutionData;
import mobi.weq.model.SensorObservation;
import mobi.weq.model.vo.GridVo;
import mobi.weq.util.map.Bounds;

import com.google.gson.Gson;

public class DataServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws HTTPException, IOException, ServletException {
		String current = req.getParameter("current");
		String grids = req.getParameter("grids");
		if (current != null && grids == null) {
			SensorObservation observation = null;
			try {
				System.out.println(req.getParameter("longitude") + "," + req.getParameter("latitude"));
				double lng = Double.valueOf(req.getParameter("longitude"));
				double lat = Double.valueOf(req.getParameter("latitude"));
				observation = PollutionData.getCurrentDataForPosition(lat, lng);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Gson gson = new Gson();
			String json = gson.toJson(observation);
			resp.getWriter().print(json);
		} else if (current != null && grids != null) {
			String sw = req.getParameter("southwest");
			String ne = req.getParameter("northeast");
			Bounds bounds = new Bounds(ne, sw);
			List<SensorObservation> obs = null;
			try {
				obs = PollutionData.getCurrentGridsAndObservationForPosition(bounds, new Date());
			} catch (SQLException e) {
				e.printStackTrace();
			}
			Gson gson = new Gson();
			String json = gson.toJson(new GridVo(obs));
			resp.getWriter().print(json);
		} else {
			String json = "{\"error\":\"Bad request\"}";
			resp.getWriter().print(json);
		}
	}
}
